package com.xb.cloud.common.redis.template;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class RedisClientAdvice {

	// 前缀，加在cache key 的前面，用于区分不同的项目.
	@Value("${projectPrefix}")
	private String projectPrefix;
	
	private static final Logger LOGGER =LoggerFactory.getLogger(RedisClientAdvice.class); 

	/**
	 * <p>
	 * 需要拦截方法过滤条件
	 * </p>
	 * 属于包 ： 方法注解：
	 */
	private final String POINT_CUT = "execution(* com.xb.cloud.common.redis.template.RedisClientTemplate.*(..)) "
			+ "&& !execution(* com.xb.cloud.common.redis.template.RedisClientTemplate.returnResource(..)) ";

	@Around(value = POINT_CUT)
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
		Object result = null;
		MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
		Object[] args = pjp.getArgs();
		
		

		try {
			LOGGER.debug("Invoker :"+methodSignature.getName()); 
			
			if (args != null && args.length > 0) {
				Object firstKey = args[0];
				if (firstKey instanceof String) {
					// 匹配字符串.
					if(firstKey!=null){
						args[0]=projectPrefix+args[0];
					}
					LOGGER.debug("after args[0]:"+args[0]);
				} else if (firstKey instanceof byte[]) {
					// 匹配字节数组.
					if(firstKey!=null){
						 String firstKeyStr= new String ((byte[])firstKey);
						 firstKeyStr=projectPrefix+firstKeyStr;
						 args[0]= firstKeyStr.getBytes();
					}
					LOGGER.debug("after args[0]:"+new String ((byte[])args[0]));
				}
			}
			result = pjp.proceed(args); //使用修改后的参数调用。
		} catch (Throwable e) {
			LOGGER.error("RedisClientAdvice调用出错!");
			e.printStackTrace();
			throw e;
		}

		return result;
	}
}
